<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\admin\model;
use think\Model;

/**
 * Description of Group
 *
 * @author HuangLuSen
 */
class StatusGroup extends Model {
    /**
     * 把状态添加到角色组
     * 示例: 把uid=1的用户添加到group_id为1,2的组 `AuthGroupModel->addToGroup(1,'1,2');`
     */
    public  function addToGroup($uid,$gid){
        $uid = is_array($uid)?implode(',',$uid):trim($uid,',');
        $gid = is_array($gid)?$gid:explode( ',',trim($gid,',') );

        if( isset($_REQUEST['batch']) ){
            //为单个用户批量添加用户组时,先删除旧数据
            $del = $this->where( array('auth_id'=>array('in',$uid)) )->delete();
        }
        $auth_id = explode(',',$uid);
        $add = array();
        if( $del!==false ){
            foreach ($auth_id as $u){
                //判断用户id是否合法
                if(model('auth_group')->getFieldByid($u,'id') == false){
                    $this->error = "ID为{$u}的角色不存在！";
                    return false;
                }
                foreach ($gid as $g){
                    if( is_numeric($u) && is_numeric($g) ){
                        $add[] = array('status_id'=>$g,'auth_id'=>$u);
                    }
                }
            }
            $this->saveAll($add);
        }
        if ($this->getError()) {
            if( count($auth_id)==1 && count($gid)==1 ){
                //单个添加时定制错误提示
                $this->error = "不能重复添加";
            }
            return false;
        }else{
            return true;
        }
    }
}
